/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation of class CObjectDBData
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: ObjectDBData.cpp,v 1.3 2009-09-01 12:56:27 amaula Exp $
 *
 */
#include "ObjectDBData.hpp"
#include "owndebug.h"

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
using namespace MaCI::ObjectDB;
//*****************************************************************************
OWNDEBUG_INITIALIZE_MODULENUMBER(); // Initialize module print capability
//*****************************************************************************

CObjectDBData::CObjectDBData()
  : iTimestampPtr(NULL),
    iCommandPtr(NULL)
{
  SetLastElementType(KTypeUnknown);
}
//*****************************************************************************

CObjectDBData::~CObjectDBData()
{
  // Do any cleanups here.
}
//*****************************************************************************

CObjectDBData::CObjectDBData(const CObjectDBData &aData)
  :  iTimestampPtr(NULL),
     iCommandPtr(NULL)
{
  // Call assignment operator.
  *this = aData;
}
//*****************************************************************************

CObjectDBData &CObjectDBData::operator=(const CObjectDBData &aData)
{
  // Reset
  Reset();

  // Create an internal BinBag instance
  if (CreateInternalBinBag(aData.iBinBagContainer) == false) {
    dPrint(4,"WARNING: Failed to create internal binbag for object %p from object %p",
           this, &aData);
  }
  
  // Do the decode on the buffer; it sets pointers and ... stuff :)
  if (DecodeFrom(NULL) == false) {
    dPrint(4,"Warning: Failed to Decode CObjectDBData even though assignment operator used?");
  }
  
  return *this; 
}
//*****************************************************************************

bool CObjectDBData::DecodeFrom(gim::binbag::CBinBag *aBinBag)
{
  bool result = true;
  const gim::binbag::TBinBlob *b = NULL;
  int previous_type = -1;
  
  // Store pointer and test it for NullNess. only overwrite if the
  // argument was non-NULL.
  if (aBinBag != NULL) 
    SetBinBagContainerPtr(aBinBag);

  // Parse
  if (iBinBagContainer && iBinBagContainer->Rewind()) {
    while( (b = iBinBagContainer->GetNextBinary()) && result ) {
      switch(b->type) {

      case KTypeTimestamp:
	if (iTimestampPtr == NULL && 
            b->size == sizeof(Common::TTimestamp)) {
	  iTimestampPtr = reinterpret_cast<const Common::TTimestamp *>(b->data);

	} else result = false;
	break;

      case KTypeCommand: {
        if (iCommandPtr == NULL && 
            b->size == sizeof(TCommand)) {
          iCommandPtr = reinterpret_cast<const TCommand *>(b->data); 

        } else result = false;
        break;
      }
#warning Most of decoders missing.

      default:
	// Unknown Type in BinBag. Do nothing.
	dPrint(10,"Unknown type %u, ignoring.", b->type);
        break;
      }
      
      // Store previous type
      previous_type = b->type;
    }
  } else result = false;

  // Store the result
  SetReadOnlyContainer(result);

  return result;
}
//*****************************************************************************

void CObjectDBData::Reset()
{
  // Call base class reset.
  CMaCIData::Reset();

  // Clean out. (Same values as in default constructor)
  iTimestampPtr = NULL;
  iCommandPtr = NULL;
  SetLastElementType(KTypeUnknown);
}
//*****************************************************************************

void CObjectDBData::Print(const int l) const
{
  const gim::binbag::TBinBlob *b = NULL;
  // Parse
  if (iBinBagContainer && iBinBagContainer->Rewind()) {
    while( (b = iBinBagContainer->GetNextBinary())) {
      switch(b->type) {
      case KTypeTimestamp: {
	const Common::TTimestamp *ts = 
          reinterpret_cast<const Common::TTimestamp *>(b->data);
	dPrint(l,"TTimestamp: s=%d, us=%d", 
	       ts->timestamp_s,
	       ts->timestamp_us);
	break;
      }
        
      case KTypeCommand: {
	const TCommand *ts = 
          reinterpret_cast<const TCommand *>(b->data);
	dPrint(l,"TCommand: cmd=%d, flags=%d", 
	       ts->cmd, ts->flags);
	break;
      }
	
      default:
	// Unknown Type in BinBag. Do nothing.
	dPrint(10,"Unknown type %u, ignoring.", b->type);
        break;
      }
    }
  }
}
//*****************************************************************************

bool CObjectDBData::SetTimestamp(const Common::TTimestamp &aStamp)
{
  bool result = false;
  if (!IsReadOnlyContainer() && iTimestampPtr == NULL) {
    ADDELEMENT(Common::TTimestamp, KTypeTimestamp, iTimestampPtr, aStamp);
    result = true;
  }
  return result;
}
//*****************************************************************************

bool CObjectDBData::SetCommand(const TCommand &aCmd)
{  
  bool result = false;
  if (!IsReadOnlyContainer() && iCommandPtr == NULL) {
    ADDELEMENT(TCommand, KTypeCommand, iCommandPtr, aCmd);
    result = true;
  }
  return result;
}
//*****************************************************************************

bool CObjectDBData::AddRealObjectInformation(const SRealObjectInformation &aInfo)
{
  bool result = false;
  uint8_t *ptr = NULL;
  unsigned int bytes = 0;

#warning Completely untested.

  if (!IsReadOnlyContainer()) {

    // Push ID.
    TDBObjectHandleSingle h(aInfo.id);
    iBinBagContainer->AddBinary(KTypeDBObjectHandleSingle, 
                                (const char *)&h, 
                                sizeof(h));
    
    // Push Name.
    if (aInfo.name.size()) {
      bytes = 0;
      ptr = NULL;
      TDBObjectName *on = TDBObjectName::CreateTextElement(&ptr, bytes, aInfo.name);
      iBinBagContainer->AddBinary(KTypeDBObjectName, 
                                  (const char *)on, 
                                  bytes);
      // Unconditionally destroy dynamic element.
      TDBObjectName::DestroyTextElement(on);
    }


    // Push Type
    if (aInfo.type.size()) {
      bytes = 0;
      ptr = NULL;
      TDBObjectType *ot = TDBObjectType::CreateTextElement(&ptr, bytes, aInfo.type);
      iBinBagContainer->AddBinary(KTypeDBObjectType, 
                                  (const char *)ot, 
                                  bytes);
      // Unconditionally destroy dynamic element.
      TDBObjectName::DestroyTextElement(ot);
    }


    // Push Description.
    if (aInfo.description.size()) {
      bytes = 0;
      ptr = NULL;
      TDBObjectDescription *od = TDBObjectDescription::CreateTextElement(&ptr, bytes, aInfo.description);
      iBinBagContainer->AddBinary(KTypeDBObjectDescription, 
                                  (const char *)od, 
                                  bytes);
      // Unconditionally destroy dynamic element.
      TDBObjectName::DestroyTextElement(od);
    }

    
    // ok.
    result = true;
  }
  
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

const MaCI::Common::TTimestamp *CObjectDBData::GetTimestamp(void) const
{
  return iTimestampPtr;
}
//*****************************************************************************

const TCommand *CObjectDBData::GetCommand(void) const
{
  return iCommandPtr;
}
//*****************************************************************************

const TDBObjectHandleArray *CObjectDBData::GetDBObjectHandleArray(void) const
{
  return iDBObjectHandleArrayPtr;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

#ifdef COMPILE_OBJECTDBDATA_STANDALONE_MAIN
#include <string>

int main(void)
{
  using namespace MaCI::ObjectDB;
  gim::binbag::CBinBag bb;
  CObjectDBData A;
  CObjectDBData B;
  bool r;

  printf("Carry out Encoding/Decoding test.\n");

  printf("Encoding...\n");
  // Do Encoding 
  A.EncodeTo(&bb);
  
  printf("Encode: Timestamp(1,2) ... ");
  r = A.SetTimestamp(MaCI::Common::TTimestamp(1, 2));
  assert(r == true);
  printf("OK.\n");

  /**
   * \todo Add test sections for TObjectDBEvent and TCommand
   */
  //////////////////////////////////////////////////////////
  printf("Decoding...\n");
  // Do Decoding
  B.DecodeFrom(&bb);
  printf("Decode: GetTimestamp() = (%d, %d) ... ", 
	 B.GetTimestamp()->timestamp_s, 
	 B.GetTimestamp()->timestamp_us);
  assert(B.GetTimestamp()->timestamp_s == 1);
  assert(B.GetTimestamp()->timestamp_us == 2);
  printf("Assertions OK.\n\n");

  /**
   * \todo Add test sections for TObjectDBEvent and TCommand
   */

  printf("Test complete.\n");
  

}
#endif
//*****************************************************************************
//*****************************************************************************
